package ru.ifmo.tanya.service.mock;

import ru.ifmo.tanya.core.calls.Call;
import ru.ifmo.tanya.core.calls.CallManager;
import ru.ifmo.tanya.core.users.User;
import ru.ifmo.tanya.core.users.UserManager;
import ru.ifmo.tanya.core.users.UserState;
import ru.ifmo.tanya.keepers.User2CallMapKeeper;
import ru.ifmo.tanya.keepers.UserStateKeeper;
import ru.ifmo.tanya.service.HttpService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * User: nikart
 * Date: 5/18/13
 * Time: 7:46 PM
 */
public class MockAgentAnswerService implements HttpService {

    private final UserManager userManager = new UserManager();
    private final UserStateKeeper userStateKeeper = new UserStateKeeper();
    private final CallManager callManager = new CallManager();
    private final User2CallMapKeeper user2CallMapKeeper = new User2CallMapKeeper();

    @Override
    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        String userIdString = request.getParameter("user-id");
        String action = request.getParameter("action");
        User user = userManager.getUserById(Integer.parseInt(userIdString));
        Call call = user2CallMapKeeper.getHoldingCallForUser(user);
        if (call == null) {
            writer.println("No call for this user");
            writer.close();
            return;
        }
        switch (action) {
            case "accept":
                userStateKeeper.updateState(user, UserState.ON_CALL);
                callManager.callAnswered(call, user);
                break;
            case "decline":
                userStateKeeper.updateState(user, UserState.AVAILABLE);
        }
        user2CallMapKeeper.removeHoldingCallForUser(user);
        writer.println("OK");
        writer.close();
    }
}
